package com.mew.chess.core.game.qmcs.game;

import com.mew.chess.core.game.qmcs.game.common.QmcsRoute;
import com.mew.common.entity.config.FishingQmcs;
import com.mew.common.util.NumberUtil;
import com.zebra.common.concurrent.ZebraExecutor;
import com.zebra.common.concurrent.ZebraExecutorGroup;
import lombok.Data;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class QmcsGameManager {
    private int gameId;
    private static QmcsGameManager qmcsGameManager = new QmcsGameManager();
    private Map<Integer, FishingQmcs> qmcsMap;
    private List<QmcsRoute> qmcsRoutes;

    private final Map<Integer, QmcsRoomManager> controllerMap = new HashMap<>(8);

    private ZebraExecutorGroup zebraExecutorGroup;

    private QmcsGameManager(){
    }

    public static QmcsGameManager getInstance() {
        if (qmcsGameManager == null) {
            synchronized (QmcsGameManager.class) {
                if (qmcsGameManager == null) {
                    qmcsGameManager = new QmcsGameManager();
                }
            }
        }
        return qmcsGameManager;
    }

    public void putController(QmcsRoomManager controller){
        controllerMap.put(controller.getRoomId(), controller);
    }

    public QmcsRoomManager getController(int roomId){
        return controllerMap.get(roomId);
    }

    public void initallZebraExecutorGroup(){
        int size = Runtime.getRuntime().availableProcessors()*8;
        zebraExecutorGroup = new ZebraExecutorGroup(size, "Shbz-exe");
        zebraExecutorGroup.start();
    }

    public ZebraExecutor getDisruptorByUserId(long userId) {
        int index = (int)(userId % (long)this.zebraExecutorGroup.size());
        return this.zebraExecutorGroup.getByIndex(index);
    }

    public void putQmcss(List<FishingQmcs> list){
        qmcsMap = null == qmcsMap ? new HashMap<>(NumberUtil.mapSize(list.size())) : qmcsMap;
        list.forEach(f -> qmcsMap.put(f.getId(), f));
    }

    public Collection<FishingQmcs> findFishs(){
       return qmcsMap.values();
    }

    public FishingQmcs getQmcsMap(int fishId){
        return qmcsMap.get(fishId);
    }

    public QmcsRoute findByType(int routeType){
        return qmcsRoutes.get(routeType);
    }

}
